<template>
  <div class="relationship-graph" ref="graphContainer"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  data: {
    type: Object,
    default: () => ({ nodes: [], edges: [] })
  }
});

const graphContainer = ref(null);
let chartInstance = null;

const initChart = () => {
  if (!graphContainer.value) return;
  
  if (echarts.getInstanceByDom(graphContainer.value)) {
    chartInstance = echarts.getInstanceByDom(graphContainer.value);
  } else {
    chartInstance = echarts.init(graphContainer.value);
  }
  
  const option = {
    title: {
      text: '关系图谱',
      top: 'bottom',
      left: 'right'
    },
    tooltip: {},
    legend: [{
      data: ['person', 'company'].map(function (a) {
        return a;
      })
    }],
    series: [
      {
        name: '关系网络',
        type: 'graph',
        layout: 'force',
        data: props.data.nodes.map(n => ({
          id: n.id,
          name: n.name,
          symbolSize: n.type === 'company' ? 30 : 20,
          category: n.type === 'company' ? 1 : 0,
          value: n.risk_score
        })),
        links: props.data.edges.map(e => ({
          source: e.source,
          target: e.target,
          value: e.weight
        })),
        categories: [
            { name: 'person' },
            { name: 'company' }
        ],
        roam: true,
        label: {
          show: true,
          position: 'right',
          formatter: '{b}'
        },
        force: {
          repulsion: 100
        }
      }
    ]
  };

  chartInstance.setOption(option);

  chartInstance.on('click', (params) => {
    if (params.dataType === 'node') {
        // Find original node data to get full identifier if needed
        // But we mapped id -> n.id. 
        // Assuming n.id IS the identifier or we need to pass it.
        // Let's check how data is mapped.
        // The series data uses n.id. 
        emit('node-click', params.data.id);
    }
  });
};

const emit = defineEmits(['node-click']);

watch(() => props.data, () => {
  if (chartInstance) {
    initChart(); // Re-render for simplicity
  }
}, { deep: true });

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  if (chartInstance) {
    chartInstance.dispose();
  }
});

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
</script>

<style scoped>
.relationship-graph {
  width: 100%;
  height: 100%;
  min-height: 400px;
}
</style>
